package top.purity.server.sso.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.purity.framework.common.GlobalConstant;
import top.purity.framework.common.exception.AuthException;
import top.purity.server.sso.controller.vo.LoginVO;
import top.purity.server.sso.feign.input.UserFeign;
import top.purity.server.sso.feign.input.dto.LoginDTO;
import top.purity.server.sso.service.SsoService;
import org.springframework.stereotype.Service;

/**
 * @version 1.0
 * @Author Lmh
 * @Description
 * @CreateTime 2023-09-24 18:21
 */

@Service
@Slf4j
@RequiredArgsConstructor
public class SsoServiceImpl implements SsoService {

    private static final String KEY = "80c2b40db25240ce92ee04dfe64c91f7";

    private final UserFeign userFeign;

    @Override
    public String login(LoginVO loginVO) throws AuthException {
        // 密码是先进行了两次 md5 加密，前端一次，后端一次，再对 加密后的密码 做 对称加密
        // 注册流程也是如此，前端注册时先对 密码 进行 md5 加密一次，再传到后端，后端再 md5 一次，再做对称加密，最终落库的是 对称加密后的密码
        // 这里就模拟，直接后端加两次，密码是 123456
        String s = SecureUtil.md5(loginVO.getPassword());
        String s1 = SecureUtil.md5(s);
        String ciphertext = SaSecureUtil.aesEncrypt(KEY, s1);
        LoginDTO loginDTO = userFeign.getByUsername(loginVO.getUsername(), loginVO.getTenantCode());
        if (ObjUtil.isEmpty(loginDTO)) {
            throw new AuthException("不存在的用户");
        }

        if (StrUtil.equals(loginDTO.getPassword(), ciphertext)) {
            return loginDTO.getId() + GlobalConstant.LOGIN_ID_SPLIT + loginDTO.getTenantId();
        }

        throw new AuthException("密码错误");
    }
}
